package com.xr.miniprogram.controller.pay;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xr.common.constant.OrderStatusConstants;
import com.xr.common.core.controller.BaseController;
import com.xr.common.core.domain.AjaxResult;
import com.xr.common.enums.RedisDelayQueueEnum;
import com.xr.miniprogram.domain.*;
import com.xr.miniprogram.domain.vo.MiniProgramInsertOrderVO;
import com.xr.miniprogram.domain.vo.MiniProgramOrderUserVO;
import com.xr.miniprogram.domain.vo.MiniProgramOrderVO;
import com.xr.miniprogram.service.*;
import com.xr.miniprogram.tools.RedissonUtil.RedisDelayQueueUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * description: 订单
 *
 * @author: wls
 * @date: 2023/9/1 14:53
 * @version:1.0
 */
@Api("订单控制")
@RestController
@RequestMapping("/miniprogram/order")
public class MiniProgramOrderController extends BaseController {
    @Autowired
    private IMiniProgramOrderService miniProgramOrderService;
    @Resource
    private IMiniProgramOrderUserService orderUserService;
    @Resource
    private IMiniProgramRefundService refundService;
    @Resource
    private WXPayService wxPayService;
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;
    @Autowired
    private IMiniProgramOrderService orderService;

    /**
     * 新增订单
     * @param
     * @return
     */
    @ApiOperation("新增订单")
    @RequestMapping("/adds")
    public AjaxResult adds(@ApiParam(value = "订单对象", required = true) @RequestBody MiniProgramInsertOrderVO miniProgramInsertOrderVO) throws Exception {
        return success(orderService.add(miniProgramInsertOrderVO));
    }

    /**
     * 根据订单id查询orderVO
     * @param orderId
     * @return
     */
    @ApiOperation("根据id查询订单")
    @GetMapping("/getById/{orderId}")
    public AjaxResult selectByOrderId(@ApiParam(value = "订单id", required = true) @PathVariable("orderId") Long orderId)
    {
        return success(miniProgramOrderService.selectMiniProgramOrderByOrderId(orderId));
    }

    /**
     * 分页查询订单树形列表
     * @param
     * @return
     */
    @ApiOperation("分页查询订单树形列表")
    @RequestMapping("/select")
    public AjaxResult selects(@ApiParam(value = "查询条件-封装对象") MiniProgramOrderVO miniProgramOrderVO,@ApiParam(value = "查询条件-订单状态编号") Long statusCode,
                              @ApiParam(value = "查询条件-订单用户状态id") Long uStatusId,@ApiParam(value = "查询条件-页数") Long pageNum,@ApiParam(value = "查询条件-数据量") Long pageSize, String staffName)
    {
        IPage<MiniProgramOrderVO> orderList = miniProgramOrderService.selectMiniProgramOrderList(new Page<>(pageNum,pageSize),miniProgramOrderVO.toMiniProgramOrder(),statusCode,uStatusId,staffName);
        return success(orderList);
    }

    /**
     * 订单超时处理
     * @param
     * @return
     */
    @ApiOperation("订单超时处理")
    @GetMapping("/timeOut/{orderNumber}")
    public AjaxResult timeOutOrder(@ApiParam(value = "订单编号") @PathVariable("orderNumber") String orderNumber)
    {
        try {
            //消费延迟队列
            redisDelayQueueUtil.removeDelayedQueue(orderNumber, RedisDelayQueueEnum.orderPaymentTimeout.getCode());
            wxPayService.checkOrderStatus(orderNumber);
        } catch (Exception e) {
            return success(e);
        }
        return success();
    }

    /**
     * 预约服务
     * @return
     */
    @ApiOperation("预约服务")
    @Transactional
    @PostMapping("/reservation")
    public AjaxResult reservationService(@ApiParam(value = "订单用户对象") @RequestBody MiniProgramOrderUserVO miniProgramOrderUserVO)
    {
        //1.改变被预约 orderUserVO 状态
        MiniProgramOrderUser orderUser = miniProgramOrderUserVO.toMiniProgramOrderUser(miniProgramOrderUserVO);
        orderUser.setOrderStatusId(OrderStatusConstants.ALLOCATION_ORDER);
        //修改所属order 剩余服务次数
        MiniProgramOrder order = miniProgramOrderService.getById(orderUser.getOrderId());
        order.setServiceNumSurplus(order.getServiceNumSurplus()-1);
        return success(orderUserService.updateById(orderUser) && miniProgramOrderService.updateById(order));
    }

    /**
     * 申请退款
     * @return
     */
    @ApiOperation("申请退款")
    @Transactional
    @PostMapping("/refund")
    public AjaxResult refund(@RequestBody Map<String,String> params)
    {
        String orderNumber = params.get("orderNumber");
        String reason = params.get("reason");
        //查询是否已有退款单
        MiniProgramRefund miniProgramRefund = refundService.getRefundByOrderNumber(orderNumber);
        if(miniProgramRefund == null){//没有退款单
            //根据订单编号创建退款单
            refundService.createRefundByOrderNo(orderNumber,reason);
        }else{//已有退款单
            miniProgramRefund.setReason(reason);
        }
        orderService.updateStatusByOrderNo(orderNumber,OrderStatusConstants.REFUND_ORDER);
        return success();
    }

    /**
     * 取消退款
     * @return
     */
    @ApiOperation("取消退款")
    @Transactional
    @PostMapping("/cancelRefund/{orderNumber}")
    public AjaxResult cancelRefund(@PathVariable("orderNumber") String orderNumber)
    {
        orderService.updateStatusByOrderNo(orderNumber,OrderStatusConstants.SERVICE_ORDER);
        return success();
    }

    /**
     * 更新订单子项
     * @param miniProgramOrderUser
     * @return
     */
    @PostMapping("/updateOrderUser")
    public AjaxResult updateOrderUser(@RequestBody MiniProgramOrderUser miniProgramOrderUser)
    {
        return success(orderUserService.updateOrderUser(miniProgramOrderUser));
    }

    /**
     * 主动调用-支付成功处理
     * @return
     */
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody MiniProgramOrder miniProgramOrder)
    {
        String orderNumber = miniProgramOrder.getOrderNumber();
        orderService.updateStatusByOrderNo(orderNumber,OrderStatusConstants.SERVICE_ORDER);
        return success();
    }



}
